package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserAddressMapper;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: lx
 * @Time: 10:10
 * @Description:
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;
    //检验用户名密码是否正确
    @Override
    public UserInfo login(UserInfo userInfo) {
        //1：根据登录名 查询此用户是否存在   无此用户
        //2: 有此用户 检验密码  加密了之后再校验
        UserInfo userInfo1 = userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
                        .eq("login_name", userInfo.getLoginName()));
        if(null != userInfo1 && MD5.encrypt(
                userInfo.getPasswd()).equals(userInfo1.getPasswd())){

                //登录成功
                return userInfo1;
        }
        //失败了
        return null;
    }

    @Autowired
    private UserAddressMapper userAddressMapper;
    //查询地址集合
    @Override
    public List<UserAddress> findUserAddressList() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String userId = AuthContextHolder.getUserId(request);
        return userAddressMapper.selectList(new QueryWrapper<UserAddress>()
        .eq("user_id",userId));

    }

    public static void main(String[] args) {
        System.out.println(MD5.encrypt("123"));
    }
}
